/**
 * WebGPU Batch Render Bindings Implementation
 * 参考Cocos JSB 2.0实现的具体绑定代码
 */

#include "webgpu_batch_bindings.h"
#include "cocos/bindings/manual/jsb_conversions.h"
#include "cocos/bindings/manual/jsb_global.h"
#include <dawn/dawn_native/DawnNative.h>
#include <chrono>
#include <algorithm>

namespace webgpu {

// ResourceLifecycleManager 实现
ResourceLifecycleManager::ResourceLifecycleManager()
    : maxMemoryUsage_(1024 * 1024 * 1024), // 1GB默认限制
      cleanupThreshold_(1000),
      autoCleanupEnabled_(true) {
}

ResourceLifecycleManager::~ResourceLifecycleManager() {
    cleanup();
}

void ResourceLifecycleManager::registerResource(uint32_t id, ResourceType type, const std::string& label) {
    std::lock_guard<std::mutex> lock(resourceMutex_);
    resources_.emplace(id, ResourceInfo(id, type, label));

    SE_LOGD("Registered resource: ID=%u, Type=%d, Label=%s", id, static_cast<int>(type), label.c_str());
}

void ResourceLifecycleManager::unregisterResource(uint32_t id) {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto it = resources_.find(id);
    if (it != resources_.end()) {
        // 清理依赖关系
        updateDependencies(id);

        // 更新内存统计
        {
            std::lock_guard<std::mutex> statsLock(statsMutex_);
            memoryByType_[it->second.type] -= it->second.memorySize;
        }

        SE_LOGD("Unregistered resource: ID=%u", id);
        resources_.erase(it);
    }
}

void ResourceLifecycleManager::addReference(uint32_t id) {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto it = resources_.find(id);
    if (it != resources_.end()) {
        it->second.refCount++;
        it->second.lastAccessTime = std::chrono::steady_clock::now();
        SE_LOGD("Added reference to resource: ID=%u, RefCount=%u", id, it->second.refCount);
    }
}

void ResourceLifecycleManager::removeReference(uint32_t id) {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto it = resources_.find(id);
    if (it != resources_.end() && it->second.refCount > 0) {
        it->second.refCount--;
        SE_LOGD("Removed reference from resource: ID=%u, RefCount=%u", id, it->second.refCount);

        // 自动清理引用计数为0的资源
        if (autoCleanupEnabled_ && it->second.refCount == 0 && canDestroy(id)) {
            it->second.state = ResourceState::PendingDestroy;
        }
    }
}

uint32_t ResourceLifecycleManager::getReferenceCount(uint32_t id) const {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto it = resources_.find(id);
    return it != resources_.end() ? it->second.refCount : 0;
}

void ResourceLifecycleManager::addDependency(uint32_t dependentId, uint32_t dependencyId) {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto dependentIt = resources_.find(dependentId);
    auto dependencyIt = resources_.find(dependencyId);

    if (dependentIt != resources_.end() && dependencyIt != resources_.end()) {
        dependentIt->second.dependencies.push_back(dependencyId);
        dependencyIt->second.dependents.push_back(dependentId);

        SE_LOGD("Added dependency: %u depends on %u", dependentId, dependencyId);
    }
}

void ResourceLifecycleManager::removeDependency(uint32_t dependentId, uint32_t dependencyId) {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto dependentIt = resources_.find(dependentId);
    if (dependentIt != resources_.end()) {
        auto& deps = dependentIt->second.dependencies;
        deps.erase(std::remove(deps.begin(), deps.end(), dependencyId), deps.end());
    }

    auto dependencyIt = resources_.find(dependencyId);
    if (dependencyIt != resources_.end()) {
        auto& deps = dependencyIt->second.dependents;
        deps.erase(std::remove(deps.begin(), deps.end(), dependentId), deps.end());
    }
}

void ResourceLifecycleManager::setMemorySize(uint32_t id, size_t size) {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto it = resources_.find(id);
    if (it != resources_.end()) {
        size_t oldSize = it->second.memorySize;
        it->second.memorySize = size;

        {
            std::lock_guard<std::mutex> statsLock(statsMutex_);
            memoryByType_[it->second.type] = memoryByType_[it->second.type] - oldSize + size;
        }

        checkMemoryPressure();
    }
}

size_t ResourceLifecycleManager::getTotalMemoryUsage() const {
    std::lock_guard<std::mutex> lock(statsMutex_);

    size_t total = 0;
    for (const auto& pair : memoryByType_) {
        total += pair.second;
    }
    return total;
}

void ResourceLifecycleManager::setState(uint32_t id, ResourceState state) {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    auto it = resources_.find(id);
    if (it != resources_.end()) {
        it->second.state = state;
    }
}

void ResourceLifecycleManager::cleanup() {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    std::vector<uint32_t> toDestroy;
    for (const auto& pair : resources_) {
        if (pair.second.state == ResourceState::PendingDestroy ||
            (pair.second.refCount == 0 && canDestroy(pair.first))) {
            toDestroy.push_back(pair.first);
        }
    }

    for (uint32_t id : toDestroy) {
        destroyResourceInternal(id);
    }

    SE_LOGD("Cleanup completed, destroyed %zu resources", toDestroy.size());
}

bool ResourceLifecycleManager::canDestroy(uint32_t id) const {
    auto it = resources_.find(id);
    if (it == resources_.end()) return false;

    // 检查是否有其他资源依赖于此资源
    return it->second.dependents.empty();
}

void ResourceLifecycleManager::destroyResourceInternal(uint32_t id) {
    auto it = resources_.find(id);
    if (it != resources_.end()) {
        it->second.state = ResourceState::Destroyed;
        updateDependencies(id);

        {
            std::lock_guard<std::mutex> statsLock(statsMutex_);
            memoryByType_[it->second.type] -= it->second.memorySize;
        }

        resources_.erase(it);
    }
}

void ResourceLifecycleManager::updateDependencies(uint32_t id) {
    auto it = resources_.find(id);
    if (it == resources_.end()) return;

    // 移除所有依赖关系
    for (uint32_t depId : it->second.dependencies) {
        auto depIt = resources_.find(depId);
        if (depIt != resources_.end()) {
            auto& dependents = depIt->second.dependents;
            dependents.erase(std::remove(dependents.begin(), dependents.end(), id), dependents.end());
        }
    }

    for (uint32_t depId : it->second.dependents) {
        auto depIt = resources_.find(depId);
        if (depIt != resources_.end()) {
            auto& dependencies = depIt->second.dependencies;
            dependencies.erase(std::remove(dependencies.begin(), dependencies.end(), id), dependencies.end());
        }
    }
}

void ResourceLifecycleManager::checkMemoryPressure() {
    if (getTotalMemoryUsage() > maxMemoryUsage_) {
        SE_LOGW("Memory pressure detected, current usage: %zu MB", getTotalMemoryUsage() / (1024 * 1024));

        if (autoCleanupEnabled_) {
            cleanup();
        }
    }
}

void ResourceLifecycleManager::dumpResourceInfo() const {
    std::lock_guard<std::mutex> lock(resourceMutex_);

    SE_LOGI("=== Resource Lifecycle Manager Debug Info ===");
    SE_LOGI("Total resources: %zu", resources_.size());
    SE_LOGI("Total memory usage: %zu MB", getTotalMemoryUsage() / (1024 * 1024));

    for (const auto& pair : resources_) {
        const auto& info = pair.second;
        SE_LOGI("Resource ID=%u, Type=%d, State=%d, RefCount=%u, Memory=%zu KB, Label=%s",
                info.id, static_cast<int>(info.type), static_cast<int>(info.state),
                info.refCount, info.memorySize / 1024, info.label.c_str());
    }
}

// 静态成员定义
std::unique_ptr<BatchRenderer> JSB_WebGPUBatch::s_batchRenderer = nullptr;
se_class_t* JSB_WebGPUBatch::s_class = nullptr;
se_object_t* JSB_WebGPUBatch::s_proto = nullptr;

// WebGPU资源类
se_class_t* JSB_WebGPUBatch::s_bufferClass = nullptr;
se_class_t* JSB_WebGPUBatch::s_textureClass = nullptr;
se_class_t* JSB_WebGPUBatch::s_pipelineLayoutClass = nullptr;
se_class_t* JSB_WebGPUBatch::s_bindGroupClass = nullptr;
se_class_t* JSB_WebGPUBatch::s_samplerClass = nullptr;
se_class_t* JSB_WebGPUBatch::s_renderPipelineClass = nullptr;
se_class_t* JSB_WebGPUBatch::s_computePipelineClass = nullptr;

// BatchRenderer 实现
BatchRenderer::BatchRenderer() : bufferPool_(50), texturePool_(30) {
    lifecycleManager_ = std::make_unique<ResourceLifecycleManager>();
}

BatchRenderer::~BatchRenderer() {
    // 执行最终清理
    if (lifecycleManager_) {
        lifecycleManager_->dumpResourceInfo(); // 调试信息
        lifecycleManager_->cleanup();
    }

    // 清理资源池
    bufferPool_.clear();
    texturePool_.clear();

    // 清理资源
    buffers_.clear();
    textures_.clear();
    textureViews_.clear();
    samplers_.clear();
    shaderModules_.clear();
    renderPipelines_.clear();
    computePipelines_.clear();
    bindGroupLayouts_.clear();
    bindGroups_.clear();
    pipelineLayouts_.clear();
    renderBundles_.clear();
    renderBundleEncoders_.clear();
    commandEncoders_.clear();

    SE_LOGI("BatchRenderer destroyed, all resources cleaned up");
}

bool BatchRenderer::initialize() {
    // 创建Dawn实例
    WGPUInstanceDescriptor instanceDesc{};
    instance_ = wgpuCreateInstance(&instanceDesc);
    if (!instance_) {
        SE_LOGE("Failed to create WebGPU instance");
        return false;
    }
    
    // 请求适配器
    WGPURequestAdapterOptions adapterOpts{};
    adapterOpts.powerPreference = WGPUPowerPreference_HighPerformance;
    
    WGPUAdapter adapter = nullptr;
    auto callback = [](WGPURequestAdapterStatus status, WGPUAdapter result, const char* message, void* userdata) {
        if (status == WGPURequestAdapterStatus_Success) {
            *static_cast<WGPUAdapter*>(userdata) = result;
        } else {
            SE_LOGE("Failed to request adapter: %s", message);
        }
    };
    
    wgpuInstanceRequestAdapter(instance_, &adapterOpts, callback, &adapter);
    
    // 同步等待适配器请求完成
    while (!adapter) {
        wgpuInstanceProcessEvents(instance_);
    }
    
    adapter_ = adapter;
    
    // 请求设备
    WGPUDeviceDescriptor deviceDesc{};
    deviceDesc.label = "WebGPU Batch Renderer Device";
    
    WGPUDevice device = nullptr;
    auto deviceCallback = [](WGPURequestDeviceStatus status, WGPUDevice result, const char* message, void* userdata) {
        if (status == WGPURequestDeviceStatus_Success) {
            *static_cast<WGPUDevice*>(userdata) = WGPUDevice::Acquire(result);
        } else {
            SE_LOGE("Failed to request device: %s", message);
        }
    };
    
    wgpuAdapterRequestDevice(adapter_, &deviceDesc, deviceCallback, &device);
    
    // 同步等待设备请求完成
    while (!device) {
        wgpuInstanceProcessEvents(instance_);
    }
    
    device_ = device;
    wgpuDeviceSetUncapturedErrorCallback(device_, onDeviceError, this);
    
    queue_ = wgpuDeviceGetQueue(device_);
    
    SE_LOGI("WebGPU BatchRenderer initialized successfully");
    return true;
}

void BatchRenderer::processBatch(const uint8_t* data, size_t size) {
    const uint8_t* current = data;
    size_t remaining = size;
    
    while (remaining >= sizeof(CommandHeader)) {
        processCommand(current, remaining);
    }
    
    // 处理完所有命令后，如果有待提交的命令缓冲区，则提交
    if (!pendingCommandBuffers_.empty()) {
        wgpuQueueSubmit(queue_, pendingCommandBuffers_.size(), pendingCommandBuffers_.data());
        pendingCommandBuffers_.clear();
    }

    // 执行资源清理
    performResourceCleanup();
}

void BatchRenderer::processCommand(const uint8_t*& data, size_t& remaining) {
    if (remaining < sizeof(CommandHeader)) {
        SE_LOGE("Invalid command: not enough data for header");
        return;
    }
    
    const CommandHeader* header = reinterpret_cast<const CommandHeader*>(data);
    CommandType type = static_cast<CommandType>(header->type);
    
    data += sizeof(CommandHeader);
    remaining -= sizeof(CommandHeader);
    
    switch (type) {
        case CommandType::CREATE_BUFFER:
            handleCreateBuffer(data, remaining);
            break;
        case CommandType::DESTROY_BUFFER:
            handleDestroyBuffer(data, remaining);
            break;
        case CommandType::WRITE_BUFFER:
            handleWriteBuffer(data, remaining);
            break;
        case CommandType::CREATE_TEXTURE:
            handleCreateTexture(data, remaining);
            break;
        case CommandType::CREATE_TEXTURE_VIEW:
            handleCreateTextureView(data, remaining);
            break;
        case CommandType::CREATE_SAMPLER:
            handleCreateSampler(data, remaining);
            break;
        case CommandType::CREATE_SHADER_MODULE:
            handleCreateShaderModule(data, remaining);
            break;
        case CommandType::CREATE_RENDER_PIPELINE:
            handleCreateRenderPipeline(data, remaining);
            break;
        case CommandType::CREATE_COMPUTE_PIPELINE:
            handleCreateComputePipeline(data, remaining);
            break;
        case CommandType::CREATE_BIND_GROUP_LAYOUT:
            handleCreateBindGroupLayout(data, remaining);
            break;
        case CommandType::CREATE_BIND_GROUP:
            handleCreateBindGroup(data, remaining);
            break;
        case CommandType::CREATE_PIPELINE_LAYOUT:
            handleCreatePipelineLayout(data, remaining);
            break;
        case CommandType::CREATE_RENDER_BUNDLE_ENCODER:
            handleCreateRenderBundleEncoder(data, remaining);
            break;
        case CommandType::FINISH_RENDER_BUNDLE_ENCODER:
            handleFinishRenderBundleEncoder(data, remaining);
            break;
        case CommandType::WRITE_TEXTURE:
            handleWriteTexture(data, remaining);
            break;
        case CommandType::COPY_BUFFER:
            handleCopyBufferToBuffer(data, remaining);
            break;
        case CommandType::COPY_TEXTURE:
            handleCopyTextureToTexture(data, remaining);
            break;
        case CommandType::BEGIN_RENDER_PASS:
            handleBeginRenderPass(data, remaining);
            break;
        case CommandType::END_RENDER_PASS:
            handleEndRenderPass(data, remaining);
            break;
        case CommandType::BEGIN_COMPUTE_PASS:
            handleBeginComputePass(data, remaining);
            break;
        case CommandType::END_COMPUTE_PASS:
            handleEndComputePass(data, remaining);
            break;
        case CommandType::SET_PIPELINE:
            handleSetPipeline(data, remaining);
            break;
        case CommandType::SET_VERTEX_BUFFER:
            handleSetVertexBuffer(data, remaining);
            break;
        case CommandType::SET_INDEX_BUFFER:
            handleSetIndexBuffer(data, remaining);
            break;
        case CommandType::SET_BIND_GROUP:
            handleSetBindGroup(data, remaining);
            break;
        case CommandType::DRAW:
            handleDraw(data, remaining);
            break;
        case CommandType::DRAW_INDEXED:
            handleDrawIndexed(data, remaining);
            break;
        case CommandType::SET_VIEWPORT:
            handleSetViewport(data, remaining);
            break;
        case CommandType::SET_SCISSOR_RECT:
            handleSetScissorRect(data, remaining);
            break;
        case CommandType::SET_BLEND_CONSTANT:
            handleSetBlendConstant(data, remaining);
            break;
        case CommandType::SET_STENCIL_REFERENCE:
            handleSetStencilReference(data, remaining);
            break;
        case CommandType::EXECUTE_BUNDLES:
            handleExecuteBundles(data, remaining);
            break;
        case CommandType::BUNDLE_SET_PIPELINE:
            handleBundleSetPipeline(data, remaining);
            break;
        case CommandType::BUNDLE_SET_VERTEX_BUFFER:
            handleBundleSetVertexBuffer(data, remaining);
            break;
        case CommandType::BUNDLE_SET_INDEX_BUFFER:
            handleBundleSetIndexBuffer(data, remaining);
            break;
        case CommandType::BUNDLE_SET_BIND_GROUP:
            handleBundleSetBindGroup(data, remaining);
            break;
        case CommandType::BUNDLE_DRAW:
            handleBundleDraw(data, remaining);
            break;
        case CommandType::BUNDLE_DRAW_INDEXED:
            handleBundleDrawIndexed(data, remaining);
            break;
        case CommandType::DISPATCH:
            handleDispatch(data, remaining);
            break;
        case CommandType::CREATE_COMMAND_ENCODER:
            handleCreateCommandEncoder(data, remaining);
            break;
        case CommandType::FINISH_COMMAND_ENCODER:
            handleFinishCommandEncoder(data, remaining);
            break;
        case CommandType::SUBMIT:
            handleSubmit(data, remaining);
            break;
        default:
            SE_LOGE("Unknown command type: %d", static_cast<int>(type));
            break;
    }
}

void BatchRenderer::handleCreateBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    uint32_t size = readUInt32(data, remaining);
    uint32_t usage = readUInt32(data, remaining);
    uint8_t mappedAtCreation = readUInt8(data, remaining);

    WGPUBufferDescriptor desc{};
    desc.size = size;
    desc.usage = static_cast<WGPUBufferUsage>(usage);
    desc.mappedAtCreation = mappedAtCreation != 0;

    WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &desc);
    buffers_[id] = buffer;

    // 注册到生命周期管理器
    registerResource(id, ResourceType::Buffer);
    setResourceMemorySize(id, ResourceType::Buffer, calculateBufferMemorySize(desc));

    SE_LOGD("Created buffer: ID=%u, Size=%u bytes", id, size);
}

void BatchRenderer::handleDestroyBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    
    auto it = buffers_.find(id);
    if (it != buffers_.end()) {
        wgpuBufferRelease(it->second);
        buffers_.erase(it);
    }
}

void BatchRenderer::handleWriteBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t bufferId = readUInt32(data, remaining);
    uint32_t offset = readUInt32(data, remaining);
    std::vector<uint8_t> bufferData = readBuffer(data, remaining);
    
    auto it = buffers_.find(bufferId);
    if (it != buffers_.end()) {
        wgpuQueueWriteBuffer(queue_, it->second, offset, bufferData.data(), bufferData.size());
    }
}

void BatchRenderer::handleCreateShaderModule(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    std::string code = readString(data, remaining);
    
    WGPUShaderModuleWGSLDescriptor wgslDesc{};
    wgslDesc.code = code.c_str();
    
    WGPUShaderModuleDescriptor desc{};
    desc.nextInChain = &wgslDesc;
    
    WGPUShaderModule module = wgpuDeviceCreateShaderModule(device_, &desc);
    shaderModules_[id] = module;
}

void BatchRenderer::handleBeginRenderPass(const uint8_t*& data, size_t& remaining) {
    // 如果没有命令编码器，创建一个
    if (!currentEncoder_) {
        WGPUCommandEncoderDescriptor encoderDesc{};
        currentEncoder_ = wgpuDeviceCreateCommandEncoder(device_, &encoderDesc);
    }

    // 解析渲染通道描述符
    uint32_t colorAttachmentCount = readUInt32(data, remaining);

    std::vector<WGPURenderPassColorAttachment> colorAttachments(colorAttachmentCount);

    for (uint32_t i = 0; i < colorAttachmentCount; ++i) {
        uint8_t hasAttachment = readUInt8(data, remaining);
        if (hasAttachment) {
            uint32_t textureViewId = readUInt32(data, remaining);

            // 获取实际的纹理视图
            auto viewIt = textureViews_.find(textureViewId);
            if (viewIt != textureViews_.end()) {
                colorAttachments[i].view = viewIt->second;

                // 读取清除值
                uint8_t hasClearValue = readUInt8(data, remaining);
                if (hasClearValue) {
                    colorAttachments[i].clearValue.r = readFloat32(data, remaining);
                    colorAttachments[i].clearValue.g = readFloat32(data, remaining);
                    colorAttachments[i].clearValue.b = readFloat32(data, remaining);
                    colorAttachments[i].clearValue.a = readFloat32(data, remaining);
                }

                // 读取加载和存储操作（现在是数字枚举）
                uint32_t loadOpValue = readUInt32(data, remaining);
                uint32_t storeOpValue = readUInt32(data, remaining);
                colorAttachments[i].loadOp = deserializeLoadOp(loadOpValue);
                colorAttachments[i].storeOp = deserializeStoreOp(storeOpValue);
            }
        } else {
            colorAttachments[i].view = nullptr;
        }
    }

    // 解析深度模板附件
    uint8_t hasDepthStencil = readUInt8(data, remaining);
    WGPURenderPassDepthStencilAttachment depthStencilAttachment{};

    if (hasDepthStencil) {
        uint32_t depthViewId = readUInt32(data, remaining);
        auto viewIt = textureViews_.find(depthViewId);
        if (viewIt != textureViews_.end()) {
            depthStencilAttachment.view = viewIt->second;

            // 深度操作（数字枚举）
            uint32_t depthLoadOpValue = readUInt32(data, remaining);
            uint32_t depthStoreOpValue = readUInt32(data, remaining);
            depthStencilAttachment.depthLoadOp = deserializeLoadOp(depthLoadOpValue);
            depthStencilAttachment.depthStoreOp = deserializeStoreOp(depthStoreOpValue);
            depthStencilAttachment.depthClearValue = readFloat32(data, remaining);

            // 模板操作（数字枚举）
            uint32_t stencilLoadOpValue = readUInt32(data, remaining);
            uint32_t stencilStoreOpValue = readUInt32(data, remaining);
            depthStencilAttachment.stencilLoadOp = deserializeLoadOp(stencilLoadOpValue);
            depthStencilAttachment.stencilStoreOp = deserializeStoreOp(stencilStoreOpValue);
            depthStencilAttachment.stencilClearValue = readUInt32(data, remaining);
        }
    }

    // 读取遮挡查询集合
    uint8_t hasOcclusionQuerySet = readUInt8(data, remaining);
    if (hasOcclusionQuerySet) {
        // TODO: 处理遮挡查询集合
        readUInt32(data, remaining); // 查询集合ID
    }

    // 读取时间戳写入集合
    uint8_t hasTimestampWrites = readUInt8(data, remaining);
    if (hasTimestampWrites) {
        // TODO: 处理时间戳写入集合
        uint32_t querySetCount = readUInt32(data, remaining);
        for (uint32_t i = 0; i < querySetCount; ++i) {
            readUInt32(data, remaining); // 查询集合ID
            readUInt32(data, remaining); // 查询索引
        }
    }

    WGPURenderPassDescriptor renderPassDesc{};
    renderPassDesc.colorAttachmentCount = colorAttachmentCount;
    renderPassDesc.colorAttachments = colorAttachments.data();

    if (hasDepthStencil) {
        renderPassDesc.depthStencilAttachment = &depthStencilAttachment;
    }

    currentRenderPass_ = wgpuCommandEncoderBeginRenderPass(currentEncoder_, &renderPassDesc);
}

void BatchRenderer::handleEndRenderPass(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    wgpuRenderPassEncoderEnd(renderPass_[renderPassId]);
}

void BatchRenderer::handleSetPipeline(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t pipelineId = readUInt32(data, remaining);

    wgpuRenderPassEncoderSetPipeline(renderPass_[renderPassId], renderPipeline_[pipelineId]);
}

void BatchRenderer::handleSetVertexBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t slot = readUInt32(data, remaining);
    uint32_t bufferId = readUInt32(data, remaining);
    uint32_t offset = readUInt32(data, remaining);
    uint32_t size = readUInt32(data, remaining);
    
    wgpuRenderPassEncoderSetVertexBuffer(renderPass_[renderPassId], slot, buffers_[bufferId], offset, size);
}

void BatchRenderer::handleSetVertexBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t slot = readUInt32(data, remaining);
    uint32_t bufferId = readUInt32(data, remaining);
    uint32_t offset = readUInt32(data, remaining);
    uint32_t size = readUInt32(data, remaining);
    
    wgpuRenderPassEncoderSetVertexBuffer(renderPass_[renderPassId], slot, buffers_[bufferId], offset, size);
}

void BatchRenderer::handleSetIndexBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t bufferId = readUInt32(data, remaining);
    uint32_t format = readUInt32(data, remaining);
    uint32_t offset = readUInt32(data, remaining);
    uint32_t size = readUInt32(data, remaining);
    
    wgpuRenderPassEncoderSetIndexBuffer(renderPass_[renderPassId], buffers_[bufferId], format, offset, size);
}

void BatchRenderer::handleDraw(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t vertexCount = readUInt32(data, remaining);
    uint32_t instanceCount = readUInt32(data, remaining);
    uint32_t firstVertex = readUInt32(data, remaining);
    uint32_t firstInstance = readUInt32(data, remaining);
    
    wgpuRenderPassEncoderDraw(renderPass_[renderPassId], vertexCount, instanceCount, firstVertex, firstInstance);
}

void BatchRenderer::handleDrawIndexed(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t vertexCount = readUInt32(data, remaining);
    uint32_t instanceCount = readUInt32(data, remaining);
    uint32_t firstVertex = readUInt32(data, remaining);
    uint32_t baseVertex = readUInt32(data, remaining);
    uint32_t firstInstance = readUInt32(data, remaining);
    
    wgpuRenderPassEncoderDrawIndexed(renderPass_[renderPassId], vertexCount, instanceCount, firstVertex, baseVertex, firstInstance);
}

void BatchRenderer::handleSetViewport(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t x = readFloat32(data, remaining);
    uint32_t y = readFloat32(data, remaining);
    uint32_t w = readFloat32(data, remaining);
    uint32_t h = readFloat32(data, remaining);
    uint32_t minDepth = readFloat32(data, remaining);
    uint32_t maxDepth = readFloat32(data, remaining);
    
    wgpuRenderPassEncoderSetViewport(renderPass_[renderPassId], floor(x), floor(y), floor(w), floor(h), minDepth, maxDepth);
}

void BatchRenderer::handleSetScissorRect(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t x = readFloat32(data, remaining);
    uint32_t y = readFloat32(data, remaining);
    uint32_t w = readFloat32(data, remaining);
    uint32_t h = readFloat32(data, remaining);
    
    wgpuRenderPassEncoderSetScissorRect(renderPass_[renderPassId], x, y, w, h);
}

void BatchRenderer::handleSetBlendConstant(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    WGPUColor color;
    color.r = readFloat32(data, remaining);
    color.g = readFloat32(data, remaining);
    color.b = readFloat32(data, remaining);
    color.a = readFloat32(data, remaining);
    
    wgpuRenderPassEncoderSetBlendConstant(renderPass_[renderPassId], color);
}

void BatchRenderer::handleSetStencilRefrence(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t refrence = readUint32(data, remaining);
    
    wgpuRenderPassEncoderSetStencilRefrence(renderPass_[renderPassId], refrence);
}


void BatchRenderer::handleSubmit(const uint8_t*& data, size_t& remaining) {
    uint32_t commandBufferCount = readUInt32(data, remaining);

    if (currentEncoder_) {
        WGPUCommandBuffer commandBuffer = wgpuCommandEncoderFinish(currentEncoder_);
        pendingCommandBuffers_.push_back(commandBuffer);
        currentEncoder_ = nullptr;
    }
}

// 新增的命令处理函数框架
void BatchRenderer::handleCreateTexture(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    std::string label = readString(data, remaining);

    // 读取纹理大小
    uint32_t width = readUInt32(data, remaining);
    uint32_t height = readUInt32(data, remaining);
    uint32_t depthOrArrayLayers = readUInt32(data, remaining);

    uint32_t mipLevelCount = readUInt32(data, remaining);
    uint32_t sampleCount = readUInt32(data, remaining);

    // 读取数字枚举（从JS层传递的）
    uint32_t dimensionValue = readUInt32(data, remaining);
    uint32_t formatValue = readUInt32(data, remaining);
    uint32_t usage = readUInt32(data, remaining);

    // 读取视图格式
    uint32_t viewFormatCount = readUInt32(data, remaining);
    std::vector<WGPUTextureFormat> viewFormats;
    for (uint32_t i = 0; i < viewFormatCount; ++i) {
        uint32_t formatValue = readUInt32(data, remaining);
        viewFormats.push_back(deserializeTextureFormat(formatValue));
    }

    // 创建纹理描述符
    WGPUTextureDescriptor desc{};
    desc.label = label.c_str();
    desc.size = {width, height, depthOrArrayLayers};
    desc.mipLevelCount = mipLevelCount;
    desc.sampleCount = sampleCount;
    desc.dimension = deserializeTextureDimension(dimensionValue);
    desc.format = deserializeTextureFormat(formatValue);
    desc.usage = static_cast<WGPUTextureUsage>(usage);
    desc.viewFormatCount = viewFormatCount;
    desc.viewFormats = viewFormats.data();

    WGPUTexture texture = wgpuDeviceCreateTexture(device_, &desc);
    textures_[id] = texture;
}

void BatchRenderer::handleCreateTextureView(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    uint32_t textureId = readUInt32(data, remaining);
    std::string label = readString(data, remaining);

    // 读取数字枚举（从JS层传递的）
    uint32_t formatValue = readUInt32(data, remaining);
    uint32_t dimensionValue = readUInt32(data, remaining);
    uint32_t aspectValue = readUInt32(data, remaining);
    uint32_t baseMipLevel = readUInt32(data, remaining);
    uint32_t mipLevelCount = readUInt32(data, remaining);
    uint32_t baseArrayLayer = readUInt32(data, remaining);
    uint32_t arrayLayerCount = readUInt32(data, remaining);

    auto textureIt = textures_.find(textureId);
    if (textureIt != textures_.end()) {
        WGPUTextureViewDescriptor desc{};
        desc.label = label.empty() ? nullptr : label.c_str();

        // 使用反序列化函数将数字转换为Dawn枚举
        if (formatValue != 0) {
            desc.format = deserializeTextureFormat(formatValue);
        }
        if (dimensionValue != 0) {
            desc.dimension = deserializeTextureViewDimension(dimensionValue);
        }
        desc.aspect = deserializeTextureAspect(aspectValue);
        desc.baseMipLevel = baseMipLevel;
        desc.mipLevelCount = mipLevelCount;
        desc.baseArrayLayer = baseArrayLayer;
        desc.arrayLayerCount = arrayLayerCount;

        WGPUTextureView textureView = wgpuTextureCreateView(textureIt->second, wgpuTextureCreateView(textureIt->second, &desc;desc);
        textureViews_[id] = textureView;
    }
}

void BatchRenderer::handleCreateSampler(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    std::string label = readString(data, remaining);

    // 读取数字枚举值（从JS层传递的）
    uint32_t addressModeUValue = readUInt32(data, remaining);
    uint32_t addressModeVValue = readUInt32(data, remaining);
    uint32_t addressModeWValue = readUInt32(data, remaining);
    uint32_t magFilterValue = readUInt32(data, remaining);
    uint32_t minFilterValue = readUInt32(data, remaining);
    uint32_t mipmapFilterValue = readUInt32(data, remaining);
    float lodMinClamp = readFloat32(data, remaining);
    float lodMaxClamp = readFloat32(data, remaining);
    uint32_t compareValue = readUInt32(data, remaining);
    uint16_t maxAnisotropy = readUInt16(data, remaining);

    WGPUSamplerDescriptor desc{};
    desc.label = label.empty() ? nullptr : label.c_str();

    // 使用反序列化函数将数字转换为Dawn枚举
    desc.addressModeU = deserializeAddressMode(addressModeUValue);
    desc.addressModeV = deserializeAddressMode(addressModeVValue);
    desc.addressModeW = deserializeAddressMode(addressModeWValue);
    desc.magFilter = deserializeFilterMode(magFilterValue);
    desc.minFilter = deserializeFilterMode(minFilterValue);
    desc.mipmapFilter = deserializeMipmapFilterMode(mipmapFilterValue);
    desc.lodMinClamp = lodMinClamp;
    desc.lodMaxClamp = lodMaxClamp;
    desc.maxAnisotropy = maxAnisotropy;

    // 比较函数可能为0（表示不比较）
    if (compareValue != 0) {
        desc.compare = deserializeCompareFunction(compareValue);
    }

    WGPUSampler sampler = wgpuDeviceCreateSampler(device_, &desc);
    samplers_[id] = sampler;
}

void BatchRenderer::handleCreateBindGroupLayout(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    std::string label = readString(data, remaining);

    // 读取绑定条目
    uint32_t entryCount = readUInt32(data, remaining);
    std::vector<WGPUBindGroupLayoutEntry> entries(entryCount);

    for (uint32_t i = 0; i < entryCount; ++i) {
        entries[i].binding = readUInt32(data, remaining);
        entries[i].visibility = static_cast<WGPUShaderStage>(readUInt32(data, remaining));

        // 读取绑定类型
        uint8_t hasBuffer = readUInt8(data, remaining);
        if (hasBuffer) {
            // 读取数字枚举
            uint32_t bufferTypeValue = readUInt32(data, remaining);
            entries[i].buffer.type = deserializeBufferBindingType(bufferTypeValue);
            entries[i].buffer.hasDynamicOffset = readUInt8(data, remaining) != 0;
            entries[i].buffer.minBindingSize = readUInt32(data, remaining);
        }

        uint8_t hasSampler = readUInt8(data, remaining);
        if (hasSampler) {
            // 读取数字枚举
            uint32_t samplerTypeValue = readUInt32(data, remaining);
            entries[i].sampler.type = deserializeSamplerBindingType(samplerTypeValue);
        }

        uint8_t hasTexture = readUInt8(data, remaining);
        if (hasTexture) {
            // 读取数字枚举
            uint32_t sampleTypeValue = readUInt32(data, remaining);
            uint32_t viewDimensionValue = readUInt32(data, remaining);
            entries[i].texture.sampleType = deserializeTextureSampleType(sampleTypeValue);
            entries[i].texture.viewDimension = deserializeTextureViewDimension(viewDimensionValue);
            entries[i].texture.multisampled = readUInt8(data, remaining) != 0;
        }

        uint8_t hasStorageTexture = readUInt8(data, remaining);
        if (hasStorageTexture) {
            // 读取数字枚举
            uint32_t accessValue = readUInt32(data, remaining);
            uint32_t formatValue = readUInt32(data, remaining);
            uint32_t viewDimensionValue = readUInt32(data, remaining);
            entries[i].storageTexture.access = deserializeStorageTextureAccess(accessValue);
            entries[i].storageTexture.format = deserializeTextureFormat(formatValue);
            entries[i].storageTexture.viewDimension = deserializeTextureViewDimension(viewDimensionValue);
        }
    }

    WGPUBindGroupLayoutDescriptor desc{};
    desc.label = label.empty() ? nullptr : label.c_str();
    desc.entryCount = entryCount;
    desc.entries = entries.data();

    WGPUBindGroupLayout layout = wgpuDeviceCreateBindGroupLayout(device_, &desc);
    bindGroupLayouts_[id] = layout;
}

void BatchRenderer::handleCreateBindGroup(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    std::string label = readString(data, remaining);
    uint32_t layoutId = readUInt32(data, remaining);

    // 读取绑定条目
    uint32_t entryCount = readUInt32(data, remaining);
    std::vector<WGPUBindGroupEntry> entries(entryCount);

    for (uint32_t i = 0; i < entryCount; ++i) {
        entries[i].binding = readUInt32(data, remaining);

        uint8_t resourceType = readUInt8(data, remaining);
        switch (resourceType) {
            case 1: { // Buffer
                uint32_t bufferId = readUInt32(data, remaining);
                uint32_t offset = readUInt32(data, remaining);
                uint32_t size = readUInt32(data, remaining);

                auto bufferIt = buffers_.find(bufferId);
                if (bufferIt != buffers_.end()) {
                    entries[i].buffer = bufferIt->second;
                    entries[i].offset = offset;
                    entries[i].size = size == 0 ? UINT32_MAX : size;
                }
                break;
            }
            case 2: { // ArrayBuffer
                std::vector<uint8_t> arrayBuffer = readBuffer(data, remaining);
                // 处理ArrayBuffer...
                break;
            }
            case 3: { // TextureView
                uint32_t textureViewId = readUInt32(data, remaining);
                auto viewIt = textureViews_.find(textureViewId);
                if (viewIt != textureViews_.end()) {
                    entries[i].textureView = viewIt->second;
                }
                break;
            }
            case 4: { // Sampler
                uint32_t samplerId = readUInt32(data, remaining);
                auto samplerIt = samplers_.find(samplerId);
                if (samplerIt != samplers_.end()) {
                    entries[i].sampler = samplerIt->second;
                }
                break;
            }
        }
    }

    auto layoutIt = bindGroupLayouts_.find(layoutId);
    if (layoutIt != bindGroupLayouts_.end()) {
        WGPUBindGroupDescriptor desc{};
        desc.label = label.empty() ? nullptr : label.c_str();
        desc.layout = layoutIt->second;
        desc.entryCount = entryCount;
        desc.entries = entries.data();

        WGPUBindGroup bindGroup = wgpuDeviceCreateBindGroup(device_, &desc);
        bindGroups_[id] = bindGroup;
    }
}

void BatchRenderer::handleCreateRenderPipeline(const uint8_t*& data, size_t& remaining) {
    uint32_t id = readUInt32(data, remaining);
    std::string label = readString(data, remaining);

    WGPURenderPipelineDescriptor desc{};
    desc.label = label.empty() ? nullptr : label.c_str();

    // 读取顶点状态
    uint8_t hasVertexState = readUInt8(data, remaining);
    if (hasVertexState) {
        std::string vertexEntryPoint = readString(data, remaining);
        uint32_t vertexModuleId = readUInt32(data, remaining);

        auto vertexModuleIt = shaderModules_.find(vertexModuleId);
        if (vertexModuleIt != shaderModules_.end()) {
            WGPUVertexState vertexState{};
            vertexState.module = vertexModuleIt->second;
            vertexState.entryPoint = vertexEntryPoint.c_str();

            // 读取缓冲区布局
            uint32_t bufferCount = readUInt32(data, remaining);
            std::vector<WGPUVertexBufferLayout> buffers(bufferCount);

            for (uint32_t i = 0; i < bufferCount; ++i) {
                buffers[i].arrayStride = readUInt32(data, remaining);
                buffers[i].stepMode = static_cast<WGPUVertexStepMode>(readUInt8(data, remaining));

                uint32_t attributeCount = readUInt32(data, remaining);
                std::vector<WGPUVertexAttribute> attributes(attributeCount);

                for (uint32_t j = 0; j < attributeCount; ++j) {
                    attributes[j].format = deserializeTextureFormat(readUInt32(data, remaining));
                    attributes[j].offset = readUInt32(data, remaining);
                    attributes[j].shaderLocation = readUInt32(data, remaining);
                }

                buffers[i].attributeCount = attributeCount;
                buffers[i].attributes = attributes.data();
            }

            vertexState.bufferCount = bufferCount;
            vertexState.buffers = buffers.data();
            desc.vertex = vertexState;
        }
    }

    // 读取原始状态
    uint8_t hasPrimitiveState = readUInt8(data, remaining);
    if (hasPrimitiveState) {
        WGPUPrimitiveState primitiveState{};
        primitiveState.topology = deserializePrimitiveTopology(readUInt32(data, remaining));
        primitiveState.stripIndexFormat = deserializeIndexFormat(readUInt32(data, remaining));
        primitiveState.frontFace = deserializeFrontFace(readUInt32(data, remaining));
        primitiveState.cullMode = deserializeCullMode(readUInt32(data, remaining));
        primitiveState.unclippedDepth = readUInt8(data, remaining) != 0;
        desc.primitive = primitiveState;
    }

    // 读取深度模板状态
    uint8_t hasDepthStencilState = readUInt8(data, remaining);
    if (hasDepthStencilState) {
        WGPUDepthStencilState depthStencilState{};
        depthStencilState.format = deserializeTextureFormat(readUInt32(data, remaining));
        depthStencilState.depthWriteEnabled = readUInt8(data, remaining) != 0;
        depthStencilState.depthCompare = deserializeCompareFunction(readUInt32(data, remaining));

        // 模板前面状态
        uint8_t hasStencilFront = readUInt8(data, remaining);
        if (hasStencilFront) {
            depthStencilState.stencilFront.compare = deserializeCompareFunction(readUInt32(data, remaining));
            depthStencilState.stencilFront.failOp = deserializeStencilOperation(readUInt32(data, remaining));
            depthStencilState.stencilFront.depthFailOp = deserializeStencilOperation(readUInt32(data, remaining));
            depthStencilState.stencilFront.passOp = deserializeStencilOperation(readUInt32(data, remaining));
        }

        // 模板背面状态
        uint8_t hasStencilBack = readUInt8(data, remaining);
        if (hasStencilBack) {
            depthStencilState.stencilBack.compare = deserializeCompareFunction(readUInt32(data, remaining));
            depthStencilState.stencilBack.failOp = deserializeStencilOperation(readUInt32(data, remaining));
            depthStencilState.stencilBack.depthFailOp = deserializeStencilOperation(readUInt32(data, remaining));
            depthStencilState.stencilBack.passOp = deserializeStencilOperation(readUInt32(data, remaining));
        }

        depthStencilState.stencilReadMask = readUInt32(data, remaining);
        depthStencilState.stencilWriteMask = readUInt32(data, remaining);
        depthStencilState.depthBias = readInt32(data, remaining);
        depthStencilState.depthBiasSlopeScale = readFloat32(data, remaining);
        depthStencilState.depthBiasClamp = readFloat32(data, remaining);

        desc.depthStencil = depthStencilState;
    }

    // 读取多重采样状态
    uint8_t hasMultisampleState = readUInt8(data, remaining);
    if (hasMultisampleState) {
        WGPUMultisampleState multisampleState{};
        multisampleState.count = readUInt32(data, remaining);
        multisampleState.mask = readUInt32(data, remaining);
        multisampleState.alphaToCoverageEnabled = readUInt8(data, remaining) != 0;
        desc.multisample = multisampleState;
    }

    // 读取片段状态
    uint8_t hasFragmentState = readUInt8(data, remaining);
    if (hasFragmentState) {
        std::string fragmentEntryPoint = readString(data, remaining);
        uint32_t fragmentModuleId = readUInt32(data, remaining);

        auto fragmentModuleIt = shaderModules_.find(fragmentModuleId);
        if (fragmentModuleIt != shaderModules_.end()) {
            WGPUFragmentState fragmentState{};
            fragmentState.module = fragmentModuleIt->second;
            fragmentState.entryPoint = fragmentEntryPoint.c_str();

            // 读取颜色目标
            uint32_t targetCount = readUInt32(data, remaining);
            std::vector<WGPUColorTargetState> targets(targetCount);

            for (uint32_t i = 0; i < targetCount; ++i) {
                uint8_t hasTarget = readUInt8(data, remaining);
                if (hasTarget) {
                    targets[i].format = deserializeTextureFormat(readUInt32(data, remaining));

                    uint8_t hasBlend = readUInt8(data, remaining);
                    if (hasBlend) {
                        WGPUBlendState blend{};

                        uint8_t hasColorBlend = readUInt8(data, remaining);
                        if (hasColorBlend) {
                            blend.color.operation = deserializeBlendOperation(readUInt32(data, remaining));
                            blend.color.srcFactor = deserializeBlendFactor(readUInt32(data, remaining));
                            blend.color.dstFactor = deserializeBlendFactor(readUInt32(data, remaining));
                        }

                        uint8_t hasAlphaBlend = readUInt8(data, remaining);
                        if (hasAlphaBlend) {
                            blend.alpha.operation = deserializeBlendOperation(readUInt32(data, remaining));
                            blend.alpha.srcFactor = deserializeBlendFactor(readUInt32(data, remaining));
                            blend.alpha.dstFactor = deserializeBlendFactor(readUInt32(data, remaining));
                        }

                        blend.color.writeMask = static_cast<WGPUColorWriteMask>(readUInt32(data, remaining));
                        targets[i].blend = &blend;
                    } else {
                        targets[i].blend = nullptr;
                        targets[i].writeMask = static_cast<WGPUColorWriteMask>(readUInt32(data, remaining));
                    }
                }
            }

            fragmentState.targetCount = targetCount;
            fragmentState.targets = targets.data();
            desc.fragment = fragmentState;
        }
    }

    // 读取管线布局
    uint32_t layoutId = readUInt32(data, remaining);
    auto layoutIt = pipelineLayouts_.find(layoutId);
    if (layoutIt != pipelineLayouts_.end()) {
        desc.layout = layoutIt->second;
    }

    WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &desc);
    renderPipelines_[id] = pipeline;
}

void BatchRenderer::handleSetBindGroup(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t index = readUInt32(data, remaining);
    uint32_t bindGroupId = readUInt32(data, remaining);

    // 读取动态偏移的元数据
    uint32_t totalLength = readUInt32(data, remaining);  // 总长度
    

    wgpuRenderPassEncoderSetBindGroup(renderPass_[renderPassId], index, bindGroup_[bindGroupId],
                                              totalLength, (uint32_t *)data);
    data += totalLength;

    }
}

void BatchRenderer::handleExecuteBundles(const uint8_t*& data, size_t& remaining) {
    uint32_t bundleCount = readUInt32(data, remaining);
    std::vector<WGPURenderBundle> bundles;
    bundles.reserve(bundleCount);

    for (uint32_t i = 0; i < bundleCount; ++i) {
        uint32_t bundleId = readUInt32(data, remaining);
        auto bundleIt = renderBundles_.find(bundleId);
        if (bundleIt != renderBundles_.end()) {
            bundles.push_back(bundleIt->second);
        }
    }

    if (currentRenderPass_ && !bundles.empty()) {
        wgpuRenderPassEncoderExecuteBundles(currentRenderPass_, bundles.size(), bundles.data());
    }
}

// Render Bundle 命令处理函数
void BatchRenderer::handleBundleSetPipeline(const uint8_t*& data, size_t& remaining) {
    uint32_t bundleId = readUInt32(data, remaining);
    uint32_t pipelineId = readUInt32(data, remaining);

    auto pipelineIt = renderPipelines_.find(pipelineId);
    auto bundleIt = renderBundleEncoders_.find(bundleId);

    if (pipelineIt != renderPipelines_.end() && bundleIt != renderBundleEncoders_.end()) {
        // TODO: 实现render bundle setPipeline
        // wgpuRenderBundleEncoderSetPipeline(bundleIt->second, pipelineIt->second);
    }
}

void BatchRenderer::handleBundleSetVertexBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t bundleId = readUInt32(data, remaining);
    uint32_t slot = readUInt32(data, remaining);
    uint32_t bufferId = readUInt32(data, remaining);
    uint32_t offset = readUInt32(data, remaining);
    uint32_t size = readUInt32(data, remaining);

    auto bufferIt = buffers_.find(bufferId);
    auto bundleIt = renderBundleEncoders_.find(bundleId);

    if (bufferIt != buffers_.end() && bundleIt != renderBundleEncoders_.end()) {
        // TODO: 实现render bundle setVertexBuffer
        // wgpuRenderBundleEncoderSetVertexBuffer(bundleIt->second, slot, bufferIt->second, offset, size);
    }
}

void BatchRenderer::handleBundleSetIndexBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t bundleId = readUInt32(data, remaining);
    uint32_t bufferId = readUInt32(data, remaining);
    uint32_t format = readUInt32(data, remaining);
    uint32_t offset = readUInt32(data, remaining);
    uint32_t size = readUInt32(data, remaining);

    auto bufferIt = buffers_.find(bufferId);
    auto bundleIt = renderBundleEncoders_.find(bundleId);

    if (bufferIt != buffers_.end() && bundleIt != renderBundleEncoders_.end()) {
        // TODO: 实现render bundle setIndexBuffer
        // wgpuRenderBundleEncoderSetIndexBuffer(bundleIt->second, bufferIt->second,
        //     static_cast<WGPUIndexFormat>(format), offset, size);
    }
}

void BatchRenderer::handleBundleSetBindGroup(const uint8_t*& data, size_t& remaining) {
    uint32_t index = readUInt32(data, remaining);
    uint32_t bindGroupId = readUInt32(data, remaining);
    uint32_t offsetCount = readUInt32(data, remaining);

    std::vector<uint32_t> dynamicOffsets(offsetCount);
    for (uint32_t i = 0; i < offsetCount; ++i) {
        dynamicOffsets[i] = readUInt32(data, remaining);
    }

    uint32_t bundleId = readUInt32(data, remaining);

    auto bindGroupIt = bindGroups_.find(bindGroupId);
    auto bundleIt = renderBundleEncoders_.find(bundleId);

    if (bindGroupIt != bindGroups_.end() && bundleIt != renderBundleEncoders_.end()) {
        // TODO: 实现render bundle setBindGroup
        // wgpuRenderBundleEncoderSetBindGroup(bundleIt->second, index, bindGroupIt->second,
        //     dynamicOffsets.size(), dynamicOffsets.data());
    }
}

void BatchRenderer::handleBundleDraw(const uint8_t*& data, size_t& remaining) {
    uint32_t vertexCount = readUInt32(data, remaining);
    uint32_t instanceCount = readUInt32(data, remaining);
    uint32_t firstVertex = readUInt32(data, remaining);
    uint32_t firstInstance = readUInt32(data, remaining);
    uint32_t bundleId = readUInt32(data, remaining);

    auto bundleIt = renderBundleEncoders_.find(bundleId);
    if (bundleIt != renderBundleEncoders_.end()) {
        // TODO: 实现render bundle draw
        // wgpuRenderBundleEncoderDraw(bundleIt->second, vertexCount, instanceCount, firstVertex, firstInstance);
    }
}

void BatchRenderer::handleBundleDrawIndexed(const uint8_t*& data, size_t& remaining) {
    uint32_t indexCount = readUInt32(data, remaining);
    uint32_t instanceCount = readUInt32(data, remaining);
    uint32_t firstIndex = readUInt32(data, remaining);
    uint32_t baseVertex = readUInt32(data, remaining);
    uint32_t firstInstance = readUInt32(data, remaining);
    uint32_t bundleId = readUInt32(data, remaining);

    auto bundleIt = renderBundleEncoders_.find(bundleId);
    if (bundleIt != renderBundleEncoders_.end()) {
        // TODO: 实现render bundle drawIndexed
        // wgpuRenderBundleEncoderDrawIndexed(bundleIt->second, indexCount, instanceCount,
        //     firstIndex, baseVertex, firstInstance);
    }
}

// Render Pass 扩展方法实现
void BatchRenderer::handleSetViewport(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    float x = readFloat32(data, remaining);
    float y = readFloat32(data, remaining);
    float width = readFloat32(data, remaining);
    float height = readFloat32(data, remaining);
    float minDepth = readFloat32(data, remaining);
    float maxDepth = readFloat32(data, remaining);

    wgpuRenderPassEncoderSetViewport(renderPass_[renderPassId], x, y, width, height, minDepth, maxDepth);
}

void BatchRenderer::handleSetScissorRect(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t x = readUInt32(data, remaining);
    uint32_t y = readUInt32(data, remaining);
    uint32_t width = readUInt32(data, remaining);
    uint32_t height = readUInt32(data, remaining);
    wgpuRenderPassEncoderSetScissorRect(renderPass_[renderPassId], x, y, width, height);
}

void BatchRenderer::handleSetBlendConstant(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    float r = readFloat32(data, remaining);
    float g = readFloat32(data, remaining);
    float b = readFloat32(data, remaining);
    float a = readFloat32(data, remaining);

    WGPUColor color = {r, g, b, a};
    wgpuRenderPassEncoderSetBlendConstant(renderPass_[renderPassId], &color); 
}

void BatchRenderer::handleSetStencilReference(const uint8_t*& data, size_t& remaining) {
    uint32_t renderPassId = readUInt32(data, remaining);
    uint32_t reference = readUInt32(data, remaining);

    wgpuRenderPassEncoderSetStencilReference(renderPass_[renderPassId], reference);
}

// 其他处理函数可以按需继续添加...

// 辅助函数实现

uint32_t BatchRenderer::readUInt32(const uint8_t*& data, size_t& remaining) {
    if (remaining < 4) return 0;
    uint32_t value = *reinterpret_cast<const uint32_t*>(data);
    data += 4;
    remaining -= 4;
    return value;
}

int32_t BatchRenderer::readInt32(const uint8_t*& data, size_t& remaining) {
    if (remaining < 4) return 0;
    int32_t value = *reinterpret_cast<const int32_t*>(data);
    data += 4;
    remaining -= 4;
    return value;
}

uint16_t BatchRenderer::readUInt16(const uint8_t*& data, size_t& remaining) {
    if (remaining < 2) return 0;
    uint16_t value = *reinterpret_cast<const uint16_t*>(data);
    data += 2;
    remaining -= 2;
    return value;
}

uint8_t BatchRenderer::readUInt8(const uint8_t*& data, size_t& remaining) {
    if (remaining < 1) return 0;
    uint8_t value = *data;
    data += 1;
    remaining -= 1;
    return value;
}

std::string BatchRenderer::readString(const uint8_t*& data, size_t& remaining) {
    uint32_t length = readUInt32(data, remaining);
    if (remaining < length) return {};
    
    std::string str(reinterpret_cast<const char*>(data), length);
    data += length;
    remaining -= length;
    return str;
}

std::vector<uint8_t> BatchRenderer::readBuffer(const uint8_t*& data, size_t& remaining) {
    uint32_t length = readUInt32(data, remaining);
    if (remaining < length) return {};

    std::vector<uint8_t> buffer(data, data + length);
    data += length;
    remaining -= length;
    return buffer;
}

float BatchRenderer::readFloat32(const uint8_t*& data, size_t& remaining) {
    if (remaining < 4) return 0.0f;
    float value = *reinterpret_cast<const float*>(data);
    data += 4;
    remaining -= 4;
    return value;
}

// Dawn 枚举反序列化函数实现 - 直接强转（更高效）
WGPUStoreOp BatchRenderer::deserializeStoreOp(uint32_t value) {
    return static_cast<WGPUStoreOp>(value);
}

WGPUCompareFunction BatchRenderer::deserializeCompareFunction(uint32_t value) {
    return static_cast<WGPUCompareFunction>(value);
}

WGPUStencilOperation BatchRenderer::deserializeStencilOperation(uint32_t value) {
    return static_cast<WGPUStencilOperation>(value);
}

WGPUPrimitiveTopology BatchRenderer::deserializePrimitiveTopology(uint32_t value) {
    return static_cast<WGPUPrimitiveTopology>(value);
}

WGPUFrontFace BatchRenderer::deserializeFrontFace(uint32_t value) {
    return static_cast<WGPUFrontFace>(value);
}

WGPUCullMode BatchRenderer::deserializeCullMode(uint32_t value) {
    return static_cast<WGPUCullMode>(value);
}

WGPUBlendOperation BatchRenderer::deserializeBlendOperation(uint32_t value) {
    return static_cast<WGPUBlendOperation>(value);
}

WGPUBlendFactor BatchRenderer::deserializeBlendFactor(uint32_t value) {
    return static_cast<WGPUBlendFactor>(value);
}

WGPUAddressMode BatchRenderer::deserializeAddressMode(uint32_t value) {
    return static_cast<WGPUAddressMode>(value);
}

WGPUFilterMode BatchRenderer::deserializeFilterMode(uint32_t value) {
    return static_cast<WGPUFilterMode>(value);
}

WGPUMipmapFilterMode BatchRenderer::deserializeMipmapFilterMode(uint32_t value) {
    return static_cast<WGPUMipmapFilterMode>(value);
}

WGPUTextureFormat BatchRenderer::deserializeTextureFormat(uint32_t value) {
    return static_cast<WGPUTextureFormat>(value);
}

WGPUBufferBindingType BatchRenderer::deserializeBufferBindingType(uint32_t value) {
    return static_cast<WGPUBufferBindingType>(value);
}

WGPUSamplerBindingType BatchRenderer::deserializeSamplerBindingType(uint32_t value) {
    return static_cast<WGPUSamplerBindingType>(value);
}

WGPUTextureSampleType BatchRenderer::deserializeTextureSampleType(uint32_t value) {
    return static_cast<WGPUTextureSampleType>(value);
}

WGPUTextureViewDimension BatchRenderer::deserializeTextureViewDimension(uint32_t value) {
    return static_cast<WGPUTextureViewDimension>(value);
}

WGPUStorageTextureAccess BatchRenderer::deserializeStorageTextureAccess(uint32_t value) {
    return static_cast<WGPUStorageTextureAccess>(value);
}

WGPUTextureAspect BatchRenderer::deserializeTextureAspect(uint32_t value) {
    return static_cast<WGPUTextureAspect>(value);
}

WGPUTextureDimension BatchRenderer::deserializeTextureDimension(uint32_t value) {
    return static_cast<WGPUTextureDimension>(value);
}

WGPUIndexFormat BatchRenderer::deserializeIndexFormat(uint32_t value) {
    return static_cast<WGPUIndexFormat>(value);
}

void BatchRenderer::onDeviceError(WGPUErrorType type, const char* message, void* userdata) {
    SE_LOGE("WebGPU Device Error: %s", message);
}

// BatchRenderer 资源生命周期管理方法实现
void BatchRenderer::registerResource(uint32_t id, ResourceType type, const std::string& label) {
    if (lifecycleManager_) {
        lifecycleManager_->registerResource(id, type, label);
    }
}

void BatchRenderer::addResourceDependency(uint32_t dependentId, uint32_t dependencyId) {
    if (lifecycleManager_) {
        lifecycleManager_->addDependency(dependentId, dependencyId);
    }
}

void BatchRenderer::setResourceMemorySize(uint32_t id, ResourceType type, size_t size) {
    if (lifecycleManager_) {
        lifecycleManager_->setMemorySize(id, size);
    }
}

void BatchRenderer::destroyResource(uint32_t id, ResourceType type) {
    if (lifecycleManager_) {
        lifecycleManager_->setState(id, ResourceState::PendingDestroy);
    }

    // 从相应的映射表中移除资源
    switch (type) {
        case ResourceType::Buffer:
            buffers_.erase(id);
            break;
        case ResourceType::Texture:
            textures_.erase(id);
            break;
        case ResourceType::TextureView:
            textureViews_.erase(id);
            break;
        case ResourceType::Sampler:
            samplers_.erase(id);
            break;
        case ResourceType::ShaderModule:
            shaderModules_.erase(id);
            break;
        case ResourceType::RenderPipeline:
            renderPipelines_.erase(id);
            break;
        case ResourceType::ComputePipeline:
            computePipelines_.erase(id);
            break;
        case ResourceType::BindGroupLayout:
            bindGroupLayouts_.erase(id);
            break;
        case ResourceType::BindGroup:
            bindGroups_.erase(id);
            break;
        case ResourceType::PipelineLayout:
            pipelineLayouts_.erase(id);
            break;
        case ResourceType::RenderBundle:
            renderBundles_.erase(id);
            break;
        case ResourceType::RenderBundleEncoder:
            renderBundleEncoders_.erase(id);
            break;
        case ResourceType::CommandEncoder:
            commandEncoders_.erase(id);
            break;
    }

    if (lifecycleManager_) {
        lifecycleManager_->unregisterResource(id);
    }
}

void BatchRenderer::performResourceCleanup() {
    if (lifecycleManager_) {
        lifecycleManager_->cleanup();
    }
}

// 计算资源内存大小的辅助函数
size_t calculateBufferMemorySize(const WGPUBufferDescriptor& desc) {
    return desc.size;
}

size_t calculateTextureMemorySize(const WGPUTextureDescriptor& desc) {
    // 简化的纹理大小计算，实际应该考虑格式
    size_t pixelSize = 4; // 假设RGBA8格式
    size_t totalSize = 0;

    for (uint32_t mip = 0; mip < desc.mipLevelCount; ++mip) {
        uint32_t width = std::max(1u, desc.size.width >> mip);
        uint32_t height = std::max(1u, desc.size.height >> mip);
        uint32_t depth = desc.size.depthOrArrayLayers;

        totalSize += width * height * depth * pixelSize * desc.sampleCount;
    }

    return totalSize;
}

// JSB 绑定实现
bool JSB_WebGPUBatch::init(se_object_t* obj) {
    auto lambda = [](se_object_t* obj) -> bool {
        return true;
    };
    s_class = se_class_t::create("WebGPUBatch", obj, nullptr, lambda);
    s_class->defineFinalizeFunction(_SE(JSB_WebGPUBatch_finalize));
    
    s_class->defineFunction("batchRender", _SE(webgpuBatchRender));
    s_class->defineFunction("getDevice", _SE(webgpuGetDevice));
    s_class->defineFunction("setBatchMode", _SE(webgpuSetBatchMode));
    
    s_class->install();
    JSBClassType::registerClass<BatchRenderer>(s_class);
    
    se_object_t* proto = s_class->getProto();
    if (proto) {
        s_proto = proto;
    }
    
    // 创建全局实例
    if (!s_batchRenderer) {
        s_batchRenderer = std::make_unique<BatchRenderer>();
        s_batchRenderer->initialize();

        // 初始化WebGPU资源类
        se_object_t* globalObj = se_get_global_object();
        initResourceClasses(globalObj);

        // 注册全局函数
        globalObj->setProperty("webgpuBatchRender", se_value_t(se_object_t::createPlainObject()));
    }
    
    return true;
}

void JSB_WebGPUBatch::destroy() {
    if (s_batchRenderer) {
        s_batchRenderer.reset();
    }
}

bool JSB_WebGPUBatch::webgpuBatchRender(se_state_t& s) {
    const auto& args = s.args();
    size_t argc = args.size();
    
    if (argc != 1) {
        SE_REPORT_ERROR("webgpuBatchRender expects 1 argument");
        return false;
    }
    
    // 获取TypedArray数据
    if (args[0].isObject()) {
        se_object_t* obj = args[0].toObject();
        
        uint8_t* data = nullptr;
        size_t byteLength = 0;
        
        if (obj->isTypedArray()) {
            bool success = obj->getTypedArrayData(&data, &byteLength);
            if (success && s_batchRenderer) {
                s_batchRenderer->processBatch(data, byteLength);
                return true;
            }
        }
    }
    
    SE_REPORT_ERROR("webgpuBatchRender expects a TypedArray argument");
    return false;
}

bool JSB_WebGPUBatch::webgpuGetDevice(se_state_t& s) {
    if (!s_batchRenderer) {
        s.rval().setNull();
        return true;
    }
    
    // 返回设备句柄或相关信息
    s.rval().setUint32(reinterpret_cast<uintptr_t>(s_batchRenderer->getDevice()));
    return true;
}

bool JSB_WebGPUBatch::webgpuSetBatchMode(se_state_t& s) {
    const auto& args = s.args();
    if (args.size() != 1) {
        SE_REPORT_ERROR("webgpuSetBatchMode expects 1 argument");
        return false;
    }
    
    bool batchMode = args[0].toBoolean();
    // 设置批处理模式的逻辑
    
    return true;
}

SE_IMPLEMENT_FINALIZE_FUNC(JSB_WebGPUBatch_finalize) {
    // 清理逻辑
}

// WebGPU资源通用finalize回调
SE_IMPLEMENT_FINALIZE_FUNC(JSB_WebGPUResource_finalize) {
    WebGPUResourceData* data = static_cast<WebGPUResourceData*>(ptr);
    if (data && data->renderer) {
        // 销毁native资源
        data->renderer->destroyResource(data->resourceId, data->resourceType);
        SE_LOGD("Finalized WebGPU resource: ID=%u, Type=%d", data->resourceId, static_cast<int>(data->resourceType));
    }
    delete data;
}

// 创建带finalize回调的WebGPU资源对象
se_object_t* JSB_WebGPUBatch::createResourceObject(uint32_t id, ResourceType type, const char* className) {
    se_class_t* cls = nullptr;

    switch (type) {
        case ResourceType::Buffer:
            cls = s_bufferClass;
            break;
        case ResourceType::Texture:
            cls = s_textureClass;
            break;
        case ResourceType::PipelineLayout:
            cls = s_pipelineLayoutClass;
            break;
        case ResourceType::BindGroup:
            cls = s_bindGroupClass;
            break;
        case ResourceType::Sampler:
            cls = s_samplerClass;
            break;
        case ResourceType::RenderPipeline:
            cls = s_renderPipelineClass;
            break;
        case ResourceType::ComputePipeline:
            cls = s_computePipelineClass;
            break;
        default:
            SE_LOGE("Unknown resource type: %d", static_cast<int>(type));
            return nullptr;
    }

    if (!cls) {
        SE_LOGE("Resource class not initialized for type: %d", static_cast<int>(type));
        return nullptr;
    }

    // 创建JS对象
    se_object_t* obj = se_object_t::createPlainObject();

    // 设置原型
    obj->setProto(cls->getProto());

    // 创建finalize数据
    WebGPUResourceData* data = new WebGPUResourceData(id, type, s_batchRenderer.get());

    // 设置finalize回调
    obj->setPrivateData(data);
    obj->setFinalizeCallback(_SE(JSB_WebGPUResource_finalize));

    // 设置资源ID属性
    obj->setProperty("_id", se_value_t(static_cast<int32_t>(id)));
    obj->setProperty("_resourceType", se_value_t(static_cast<int32_t>(type)));

    return obj;
}

// 初始化所有WebGPU资源类
void JSB_WebGPUBatch::initResourceClasses(se_object_t* global) {
    // GPUBuffer类
    s_bufferClass = se_class_t::create("GPUBuffer", global, nullptr, nullptr);
    s_bufferClass->defineFinalizeFunction(_SE(JSB_WebGPUResource_finalize));
    s_bufferClass->install();

    // GPUTexture类
    s_textureClass = se_class_t::create("GPUTexture", global, nullptr, nullptr);
    s_textureClass->defineFinalizeFunction(_SE(JSB_WebGPUResource_finalize));
    s_textureClass->install();

    // GPUPipelineLayout类 - 注意这里使用标准的WebGPU名字
    s_pipelineLayoutClass = se_class_t::create("GPUPipelineLayout", global, nullptr, nullptr);
    s_pipelineLayoutClass->defineFinalizeFunction(_SE(JSB_WebGPUResource_finalize));
    s_pipelineLayoutClass->install();

    // GPUBindGroup类
    s_bindGroupClass = se_class_t::create("GPUBindGroup", global, nullptr, nullptr);
    s_bindGroupClass->defineFinalizeFunction(_SE(JSB_WebGPUResource_finalize));
    s_bindGroupClass->install();

    // GPUSampler类
    s_samplerClass = se_class_t::create("GPUSampler", global, nullptr, nullptr);
    s_samplerClass->defineFinalizeFunction(_SE(JSB_WebGPUResource_finalize));
    s_samplerClass->install();

    // GPURenderPipeline类
    s_renderPipelineClass = se_class_t::create("GPURenderPipeline", global, nullptr, nullptr);
    s_renderPipelineClass->defineFinalizeFunction(_SE(JSB_WebGPUResource_finalize));
    s_renderPipelineClass->install();

    // GPUComputePipeline类
    s_computePipelineClass = se_class_t::create("GPUComputePipeline", global, nullptr, nullptr);
    s_computePipelineClass->defineFinalizeFunction(_SE(JSB_WebGPUResource_finalize));
    s_computePipelineClass->install();

    SE_LOGI("WebGPU resource classes initialized");
}

} // namespace webgpu

// C风格导出函数
extern "C" bool jsb_register_webgpu_batch(se_object_t* obj) {
    return webgpu::JSB_WebGPUBatch::init(obj);
}